<?php
namespace ac\modules\member\controllers;

use Yii;
use ac\controllers\BasicController;
use yii\web\Controller;
use app\modules\member\models\Member;
use app\modules\member\models\IntegralRecord;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;

class IntegralController extends BasicController
{
    protected $memberInfo;//登录信息

    public function init()
    {
        parent::init();
        if(isset($this->session->get('memberInfo')->loginname)){
            $this->memberInfo = $this->session->get('memberInfo');
        };
    }

    /*添加积分*/
    public function actionAddIntegral()
    {
        if(Yii::$app->request->isPost 
            and isset($this->post['member_id']) 
            and isset($this->post['app']) 
            and isset($this->post['flag']) 
            and isset($this->post['integral'])
            and isset($this->post['secretkey'])
            and $this->post['secretkey'] == $this->params['secretkey']['ac']){

            $member = Member::find()->select(['member_id', 'curr_integral'])
                            ->where('member_id = :id', [':id' => $this->post['member_id']])
                            ->one();
            // P($member);
            if(!is_null($member)){
                /*判断是否在设定的范围*/
                if(in_array($this->post['flag'], $this->params['integralRule'][$this->post['app']])){
                    $transaction = Yii::$app->db->beginTransaction();//事物处理
                    $pass = true;
                    try{
                        $this->post['integral'] = (int)$this->post['integral'];
                        if(isset($this->post['way']) and $this->post['way'] == 2){//增加积分
                            $integral = $this->post['integral'];
                        }else{//减少积分
                            $integral = 0 - $this->post['integral'];
                        }
                        if($this->post['way'] == 1 and $member->curr_integral < abs($integral)){
                            $pass = false;
                            $backInfo = ErrMap::getError(10026);//返回信息
                        }
                        /*1、增加会员积分*/
                        if($pass){
                            if( !Member::updateAllCounters(['curr_integral' => $integral], 'member_id = :memberid', [':memberid' => $member->member_id]) ){
                                $pass = false;
                                $backInfo = ErrMap::getError(10027);//返回信息
                            }
                            if(!$integral){//减少的话  需要改变 cost_integral 的值
                                if( !Member::updateAllCounters(['cost_integral' => abs($integral)], 'member_id = :memberid', [':memberid' => $member->member_id]) ){
                                    $pass = false;
                                    $backInfo = ErrMap::getError(10027);//返回信息
                                } 
                            }
                        }

                        /*2、增加积分记录*/
                        if($pass){
                            $integralRecord = new IntegralRecord;
                            $data = array(
                                'IntegralRecord' => $this->post
                            );
                            $data['IntegralRecord']['member_id'] = $member->member_id;
                            if(!$integralRecord->addRecord($data)){
                                $pass = false;
                                if($integralRecord->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $integralRecord->getErrors();//异常信息
                                }
                            }
                        }

                        if($pass){
                            $backInfo = [0, '添加积分成功'];//返回信息
                            $transaction->commit();
                        }
                    }catch(\Exception $exception){
                        $transaction->rollback();       
                    };
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*删除我的积分*/
    public function actionDelIntegral()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        /*如果没有登录，自动登录*/
        if(!isset($this->memberInfo)){
            Yii::$app->runAction('member/login/getinfo-by-openid');
        }

        
        if(isset($this->memberInfo)){
            $id = isset($this->post['id'])?$this->post['id']:'';
            if($id){
                if( IntegralRecord::updateAll(['isdel' => 2], 'rid = :id', [':id' => $id]) ){//删除成功
                    $backInfo = [0, '删除我的积分成功'];//返回信息
                }else{//删除失败
                    $backInfo = ErrMap::getError(10013, '删除我的积分失败');//返回信息
                }
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, '', $this->memberInfo), '') ) != 'boolean'){
                    return $res;
                };
            }
            return Tool::showRes(ErrMap::getError(10005));
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }

    /*获取积分流水*/
    public function actionIntegralList()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        if(isset($this->memberInfo)){
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = Tool::getPageSize();

            $integralRecord = new IntegralRecord;
            $count = $integralRecord::find()
                            ->where('isdel = 1 and member_id = :mid', [':mid' => $this->memberInfo->member_id])
                            ->count();
            $integralRecordList = $integralRecord::find()
                            ->select(['integral', 'remark', 'way', 'add_time'])
                            ->where('isdel = 1 and member_id = :mid', [':mid' => $this->memberInfo->member_id])
                            ->orderBy(['rid' => SORT_DESC])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->asArray()->all();
            $res = array(
                'list' => $integralRecordList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            // p($res);
            return Tool::showRes([0, '获取成功'], $res);
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }    

}
